package com.amc.framework.aspectj;

import com.amc.common.annotation.TimeCost;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

import java.lang.reflect.Method;

/**
 * 方法耗时统计
 *
 * @author ZhangXX
 * @date @2022/2/25 15:27
 */
@Aspect
@Component
public class TimeCostAspect {
    private static final Logger log = LoggerFactory.getLogger(TimeCostAspect.class);


    // 配置织入点
    @Pointcut("@annotation(com.amc.common.annotation.TimeCost)")
    public void timeCostPointCut() {
    }

    /**
     * 环绕通知
     *
     * @param proceedingJoinPoint
     * @return
     * @throws Throwable
     */
    @Around("timeCostPointCut()")
    public Object aroundAdvice(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {

        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        Object result = proceedingJoinPoint.proceed();
        stopWatch.stop();
        // 获得注解
        TimeCost timeCost = getAnnotationLog(proceedingJoinPoint);
        assert timeCost != null;
        log.debug("{}耗时：{} {}", timeCost.title(), (double) stopWatch.getTotalTimeMillis() / 1000.0D, "seconds");
        return result;
    }

    /**
     * 是否存在注解，如果存在就获取
     */
    private TimeCost getAnnotationLog(JoinPoint joinPoint) {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();

        if (method != null) {
            return method.getAnnotation(TimeCost.class);
        }
        return null;
    }

}
